package com.sgu6.sgu6_machine.api;

import android.util.Log;

import com.sgu6.middleware.enums.MachineCmdEnum;
import com.sgu6.middleware.event.WarningEvent;
import com.sgu6.middleware.util.HexUtil;
import com.sgu6.netty.container.ChannelContainer;
import com.sgu6.netty.container.Machine;
import com.sgu6.netty.utils.NettyHelper;
import com.sgu6.serialport.manager.SerialPortManager;
import com.sgu6.sgu6_machine.container.MachineContainer;
import com.sgu6.sgu6_machine.event.FinishOrderEvent;
import com.sgu6.sgu6_machine.event.WeightEvent;

import org.greenrobot.eventbus.EventBus;

public class WarnServiceImpl implements IWarnApi {

    private static final String TAG = WarnServiceImpl.class.getCanonicalName();
    private long startTime;//第一次出现警报时间
    private Thread thread;

    @Override
    public void overTemp(String cmd) {
        if (startTime == 0) {
            startTime = System.currentTimeMillis();
        }
        if (startTime + 5 * 60 * 100 > System.currentTimeMillis()) {
            SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(MachineCmdEnum.停止当前工作并待机.code()));
        } else {
            postWarnInfo("机器超温", 10001);
        }
    }

    @Override
    public void heatTimeout(String cmd) {
        postWarnInfo("加热超时", 10002);
    }

    @Override
    public void millTimeout(String cmd) {
        postWarnInfo("碾米超时", 10003);
        endAction(10003);
    }

    @Override
    public void dropTimeout(String cmd) {
        postWarnInfo("下米超时", 10004);
        endAction(10004);
    }

    @Override
    public void filmTimeout(String cmd) {
        postWarnInfo("拉膜超时", 10005);
        endAction(10005);
    }

    @Override
    public void sealTimeout(String cmd) {
        int finishNo = MachineContainer.orderInfoCacheDto.getFinishNo();
        MachineContainer.orderInfoCacheDto.setFinishNo(finishNo - 1);
        postWarnInfo("封膜超时", 10006);
        endAction(10006);
    }

    @Override
    public void openDoorTimeout(String cmd) {
        postWarnInfo("开门超时", 10007);
    }

    @Override
    public void closeDoorTimeout(String cmd) {
        postWarnInfo("关门超时", 10008);
    }

    @Override
    public void pickupTimeout(String cmd) {
        postWarnInfo("取货超时", 10009);
    }

    @Override
    public void sendValleyTimeout(String cmd) {
        postWarnInfo("送谷电机超时", 10010);
    }

    @Override
    public void filmFeedTimeout(String cmd) {
        postWarnInfo("送膜电机超时", 10011);
        endAction(10011);
    }

    @Override
    public void accuracyMaxStep(String cmd) {
        postWarnInfo("精度超时", 10012);
    }

    @Override
    public void branFullTimeout(String cmd) {
        postWarnInfo("糠满超时", 10013);
    }

    @Override
    public void millWeight(String cmd) {
        byte[] b = HexUtil.HexString2Bytes(cmd);
        int weight = (b[5] & 0xff) * 16 * 16 + (b[6] & 0xff);
        int finishNo = weight / MachineContainer.machineConfigDto.packageWeight;
        EventBus.getDefault().post(new WeightEvent(finishNo));
    }

    public void postWarnInfo(String warn, Integer errorCode) {
        if (!Machine.warnInfo.toString().contains(warn)) {
            Machine.warnInfo.append(" " + warn);
            if (ChannelContainer.CHANNEL != null) {
                try {
                    NettyHelper.postMsgWithErrorReq(MachineContainer.machineConfigDto.machineNo, errorCode, warn);
                } catch (Exception e) {
                    Log.e(TAG, "postWarnInfo: ", e);
                }
            }
            EventBus.getDefault().post(new WarningEvent(true, warn));
            if (!(errorCode == 10010)) {
                EventBus.getDefault().post(new FinishOrderEvent());
            }
        }
    }

    private void endAction(int errCode) {
        thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //碾米超时，送谷超时，送膜超时
//                    if (errCode!=10010 && errCode!=10011 && errCode==10003){
                    Log.i(TAG, "run: ========================");
                        SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(MachineCmdEnum.停止当前工作并待机.code()));
                        Thread.sleep(1500);
                        SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(MachineCmdEnum.手动模式.code()));
                        Thread.sleep(1500);
                        if (errCode!=10011){
                            SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(MachineCmdEnum.自动模式.code()));
                        }
//                    }
                } catch (Exception e) {
                    Log.i(TAG, "run: " + e.getLocalizedMessage());
                }
            }
        });
        thread.start();
    }
}
